package main

import (
	"awesomeProject/dao"
	"awesomeProject/handler"
	"awesomeProject/utils"

	"log"
	"net/http"
)

func main() {
	port := "80"

	// 注册路由
	http.HandleFunc("/books", handler.BooksHandler)
	http.HandleFunc("/login", handler.LoginHandler)
	http.HandleFunc("/updateToken", handler.UpdateTokenHandler)
	// 需要JWT验证的路由
	protectedMux := http.NewServeMux()
	protectedMux.HandleFunc("/jwt/bookAdd", handler.BookAddHandler)
	protectedMux.HandleFunc("/jwt/bookUpdate", handler.BookUpdateHandler)
	protectedMux.HandleFunc("/jwt/bookDel", handler.BookDelHandler)

	// 将JWT中间件应用到保护路由
	http.Handle("/jwt/", utils.JwtMiddleware(protectedMux))

	// 处理/favicon.ico请求
	http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "./static/test.ico")
	})

	fs := http.FileServer(http.Dir("./static"))
	// 处理所有以/static/开头的请求
	http.Handle("/static/", http.StripPrefix("/static/", fs))

	//处理网站默认首页放在最后，（放在最后注册，优先级最低）
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/" { //如果不是 / 路径，返回404错误
			utils.CustomError(w, "404 page not found", http.StatusNotFound)
			return
		}
		http.ServeFile(w, r, "./static/main.html")
	})
	// 启动服务
	log.Printf("服务启动成功，监听端口 %s", port)
	log.Fatal(http.ListenAndServe(":"+port, nil))

	dao.Db.Close()
}
